import argparse
import numpy as np
import torch
import torch.nn.functional as F


def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')


def getrightlori(angle_list, cor_angle):
    res = []
    angle_list = np.append(angle_list, 360.0)
    for angle in cor_angle:
        dis_list = list(map(lambda x: abs(x-angle), angle_list))
        result = dis_list.index(min(dis_list))
        result = result if result != len(angle_list)-1 else 0
        res.append(result)
    return res

def getrightlori_test(angle_list, cor_angle):
    angle_list = np.append(angle_list, 360.0)
    dis_list = list(map(lambda x: abs(x - cor_angle), angle_list))
    result = dis_list.index(min(dis_list))
    result = result if result != len(angle_list) - 1 else 0
    return result

def get_index(sat_code, grd_code):
    """
    This is a fun to get top1.5% sat images which is the nearest to each grd image.

    Arguments:
        sat_coding, grd_coding: both are 2-D tensor: [number][featuer]

    Return :
        sat_index: index of sat which is chosed to each grd
    """

    dis = 2 - 2 * np.matmul(sat_code, np.transpose(grd_code))
    top15 = int(0.015 * dis.shape[0])
    sat_index = []
    cor_index = []
    for j in range(dis.shape[0]):
        print('Building index: [%5d/%d]' % (j, dis.shape[0]))
        index = dis[:, j].argsort()[:top15]
        if j not in index:
            index[-1] = j
        np.random.shuffle(index)
        cor_index_ = np.where(index == j)[0].tolist()
        sat_index.append(index.tolist())
        cor_index.extend(cor_index_)
    return torch.tensor(sat_index), cor_index


def get_index_test(sat_code, grd_code):
    """
    This is a fun to get top1.5% sat images which is the nearest to each grd image.

    Arguments:
        sat_coding, grd_coding: both are 2-D tensor: [number][featuer]

    Return :
        sat_index: index of sat which is chosed to each grd
    """

    dis = 2 - 2 * np.matmul(sat_code, np.transpose(grd_code))
    top15 = int(0.015 * dis.shape[0])
    sat_index = []
    cor_index = []
    for j in range(dis.shape[0]):
        index = dis[:, j].argsort()[:top15]
        np.random.shuffle(index)
        if j not in index:
            cor_index_ = [-1]
        else:
            cor_index_ = np.where(index == j)[0]

        sat_index.append(index.tolist())
        cor_index.extend(cor_index_)
    return sat_index, cor_index


if __name__ == '__main__':
    dis = np.array(range(64))
    np.random.shuffle(dis)
    dis = dis.reshape((8, 8))
    dis = torch.tensor(dis)
    # dis[4][0] = -5
    print(dis)
    cor_x = 4
    cor_y = 2
    top_list = [1, 2, 3, 4]
    acc = np.array([[1, 1, 1, 1],
                    [0, 1, 1, 1],
                    [0, 0, 1, 1],
                    [0, 0, 0, 1],
                    [0, 0, 0, 0]])
    temp1 = torch.min(dis, dim=1)
    temp2 = temp1[0].argsort().detach().numpy()
    loc = np.where(temp2 == cor_x)

    for i in range(len(top_list)):
        if loc[0] <= top_list[i]:
            print(acc[i])
            break
    print(acc[-1])